<!--广告表格组件-->
<template id="creativeTable">
  <div class="portlet">
    <div class="tools flex-between">
      <div class="tools-l grid Creativesgrid" v-show="campaignsStatus !== ARCHIVED">
        <div class="grid selectCreatives">
          <a-select defaultValue="Actions" style="min-width: 128px;">
            <a-select-option value="Actions">{{$t('pro.campaigns.actions')}}</a-select-option>
            <a-select-option value="Duplicate" @click="handleCopy">{{$t('pro.campaigns.duplicate')}}</a-select-option>
            <a-select-option
              value="Start Selected"
              @click="handlechangeState(EXECUTABLE)"
            >{{$t('pro.campaigns.StartSelected')}}</a-select-option>
            <a-select-option
              value="Stop Selected"
              @click="handlechangeState(NOTACTIVE)"
            >{{$t('pro.campaigns.StopSelected')}}</a-select-option>
          </a-select>

          <a-select defaultValue="All" style="min-width: 128px;">
            <a-select-option value="All" @click="handleSelectAll">{{$t('pro.admin.All')}}</a-select-option>
            <a-select-option
              value="Active"
              @click="handleSelectActive(EXECUTABLE)"
            >{{$t('pro.campaigns.active')}}</a-select-option>
            <a-select-option
              value="Not Active"
              @click="handleSelectActive(NOTACTIVE)"
            >{{$t('pro.campaigns.notActive')}}</a-select-option>
            <a-select-option
              value="To be audited"
              @click="handleSelectActive(MODERATED)"
            >{{$t('pro.Creatives.ToBeAudited')}}</a-select-option>
          </a-select>
          <router-link :to="{path:'/bidder/editcreative/campaignid/' + campaignsId }">
            <a-button type="primary" v-text="$t('pro.Creatives.AddCreatives')"></a-button>
          </router-link>
        </div>
        <div class="buttongrid">
          <a-button
            type="primary"
            shape="circle"
            icon="setting"
            @click="onOpenChange"
            v-show="campaignsStatus !== ARCHIVED"
          />
        </div>
      </div>
    </div>

    <div class="setting-group grid" v-if="openSetting">
      <div class="setting-group-wrapper">
        <a-checkbox-group
          class="grid checkbox-grid"
          :defaultValue="plainOptions"
          @change="checkedChange"
        >
          <a-checkbox v-for="(item,index) in plainShadow" :value="index" :key="index">{{item.title}}</a-checkbox>
        </a-checkbox-group>
        <a-button
          type="primary"
          :disabled="columnsNoChange"
          @click="saveCheckbox"
          v-text="$t('pro.public.buttonSave')"
        ></a-button>
      </div>
    </div>

    <div class="table">
      <template v-if="empty">
        <a-spin :spinning="loading">
          <a-empty
            image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
          >
            <span slot="description">{{$t('pro.Editcampaigns.emptyMess')}}</span>
          </a-empty>
        </a-spin>
      </template>
      <template v-else>
        <a-table
          :loading="loading"
          :pagination="false"
          :rowSelection="campaignsStatus !== ARCHIVED?{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}:null"
          :columns="columns"
          rowKey="id"
          @change="handleTableChange"
          :dataSource="data"
          :scroll="{x: '1000'}"
        >
          <template slot="name" slot-scope="text, record" style="width: 80px">
            <a
              @click="handleEditCreatives(record)"
              style="width: 150px;
                                       overflow:hidden;
                                       white-space:nowrap;
                                       text-overflow:ellipsis;
                                       display: block"
            >{{record.name}}</a>
          </template>
          <template slot="status" slot-scope="text, record">
            <a-switch
              :checked="record.detailedState === EXECUTABLE?true:false"
              @change="handleSwitchState(record)"
              :defaultChecked="record.detailedState == MODERATED?false:true"
              checkedChildren="ON"
              unCheckedChildren="OFF"
              :disabled="record.detailedState === NOTACTIVE || record.detailedState === EXECUTABLE?false:true"
            />
          </template>
          <template slot="details" slot-scope="text, record">
            <a-badge
              style="width: 100px"
              :status="record.detailedState | statusTypeFilter"
              :text="record.detailedState | statusFilter"
            />
          </template>
          <template slot="bids" slot-scope="text">{{text?text:0}}</template>
          <template slot="pixels" slot-scope="text">{{text? text:0}}</template>
          <template slot="wins" slot-scope="text,record">{{handleWins(record)}}</template>
          <template slot="Spend" slot-scope="text">{{text?bidPrice(text):'$1.00'}}</template>
        </a-table>
        <a-pagination
          style="text-align: right;margin-top:1rem;"
          showSizeChanger
          showQuickJumper
          :pageSizeOptions="pageSizeOptions"
          :pageSize="pagination.size"
          :total="pagination.total"
          v-model="pagination.current"
          @showSizeChange="handleChange"
          @change="handleChange"
        />
      </template>
    </div>
    <!--复制广告活动的模态框-->
    <a-modal
      :title="$t('pro.campaigns.DupModelOK')"
      v-model="visibleDup"
      @ok="handleCopyOk"
      :confirmLoading="confirming"
      :okText="selectedRowKeys.length>0?$t('pro.campaigns.DupModelOK'):$t('pro.public.buttonYes')"
      :cancelText="$t('pro.public.buttonClose')"
      @cancel="handleCopyClose"
    >
      <a-table
        v-if="selectedRowKeys.length > 0"
        rowKey="name"
        size="small"
        :pagination="false"
        :loading="loading"
        bordered
        :columns="Duplicatecolumns"
        :dataSource="DuplicateData"
      >
        <a-textarea slot="newname" slot-scope="text,record" v-model="record.newname"></a-textarea>
      </a-table>
      <a-card v-else class="NotDuplicate" type="inner" :bordered="false">
        <p v-text="$t('pro.Creatives.NotDupMess')"></p>
      </a-card>
    </a-modal>
  </div>
</template>

<script>
// 用户Creatives的所有数据列
// 提取columns的标题用作checkbox设置项
import {
  changeState,
  getAllDataByPage,
  copyCreative
} from "@/api/campaigns-creative";
import { formatMoney } from "@/utils/tool";
import {
  ACTIVE,
  NOTACTIVE,
  MODERATED,
  EXECUTABLE,
  MISTAKEN,
  ARCHIVED
} from "@/utils/publicStatus";

let statusMap = {};
export default {
  name: "creativeTable",
  props: {
    campaignsId: String
  },
  data() {
    return {
      ACTIVE,
      NOTACTIVE,
      MODERATED,
      EXECUTABLE,
      MISTAKEN,
      ARCHIVED,
      pagination: {
        size: 10,
        current: 1
      }, //分页器
      pageSizeOptions: ["10", "20", "30", "40", "50"], //分页下拉列表
      confirming: false,
      empty: false,
      nowData: [],
      data: [],
      visibleDup: false,
      DuplicateData: [],
      // 表格中显示的列
      // 总可显示列
      loading: false,
      selectedRowKeys: [],
      selectedRow: {},
      openSetting: false,
      // 表格中显示的内容项：Status,Delivery,ID...，
      // 用户自定义显示的选项内容
      checkedList: [],
      // 总的表格可显示的内容项
      columnsNoChange: true,
      columns: [],
      campaignsStatus: null
    };
  },
  //筛选表格显示状态
  filters: {
    statusFilter(type) {
      return statusMap[type].text;
    },
    statusTypeFilter(type) {
      return statusMap[type].status;
    }
  },
  computed: {
    isStatus() {
      return this.$route.query.campaignsStatus;
    },
    islocale() {
      return this.$store.state.locale;
    },
    Duplicatecolumns() {
      return this.$t("pro.Creatives.Duplicatecolumns");
    },
    plainOptions() {
      return this.$t("pro.Creatives.columnsplainOptions");
    },
    plainShadow() {
      return this.$t("pro.Creatives.columnsPlainShadow");
    }
  },
  methods: {
    //判断是否为归档广告，归档广告不能进行编辑1
    handleEditCreatives(record) {
      if (record.detailedState !== ARCHIVED) {
        this.$router.push({
          path: "/bidder/editcreative/creativeid/" + record.id
        });
      } else {
        this.$message.warning(this.$t("pro.Creatives.archivedCreatives"));
        this.$router.push({
          path: "/bidder/editcreative/creativeid/" + record.id
        });
      }
    },

    handleWins(record) {
      if (record.bids !== 0) {
        let wins = record.wins / record.bids;
        return parseFloat((wins * 100).toPrecision(4)) + "%";
      } else {
        return "-";
      }
    },
    bidPrice(text) {
      return formatMoney(Number(text), 3, "$");
    },
    //改变页数的事件
    handleChange(page, pageSize) {
      this.pagination.size = pageSize;
      this.pagination.current = page;
      this.fetch();
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      let selectRow = new Object();
      this.selectedRow = selectRow[selectedRowKeys] = selectedRows;
      this.DuplicateData = this.selectedRow.map(item => {
        return { name: item.name, newname: item.name + "-Copy" };
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination;
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      });
    },
    fetch(params = {}) {
      let that = this;
      this.columns.length = 0;
      that.plainOptions.forEach(item => {
        let { campaignsStatus } = that.$route.query || {};
        if (item != 3 || campaignsStatus !== "archived") {
          that.columns.push(that.plainShadow[item]);
        }
      });
      this.empty = false;
      this.loading = true;
      params.page = this.pagination.current || 1;
      params.results = this.pagination.size || 10;
      getAllDataByPage({
        campaignsId: this.campaignsId,
        ...params
      })
        .then(res => {
          const data = res.data.data;
          this.data = data.records;
          if (data.records.length == 0) {
            this.empty = true;
          } else {
            this.pagination = data;
          }
          console.log(this.data);
        })
        .catch(err => {})
        .finally(() => {
          this.loading = false;
        });
    },
    //复制广告创意
    handleCopy() {
      this.visibleDup = true; //显示复制广告创意的模态框
    },
    //确认复制广告创意的事件
    handleCopyOk() {
      if (this.selectedRowKeys.length > 0) {
        this.confirming = !this.confirming; //开启复制按钮的广告
        let that = this;
        let copyCreativeEntityList = this.DuplicateData.map((item, index) => {
          return { copyName: item.newname, id: that.selectedRowKeys[index] };
        });
        copyCreative({
          copyCreativeEntityList
        })
          .then(res => {
            //多个复制
            if (res.data.code == 200) {
              this.confirming = !this.confirming; //关闭复制按钮的广告
              this.visibleDup = false;
              this.$message.success(this.$t("pro.campaigns.DuplicateSuccess"));
              this.fetch();
            }
          })
          .catch(err => {
            this.confirming = !this.confirming; //关闭复制按钮的广告
            this.visibleDup = false;
            this.$message.error(this.$t("pro.campaigns.DuplicateError"));
          })
          .finally(() => {
            this.loading = false;
            this.visibleDup = false;
          });
      } else {
        this.visibleDup = false;
      }
    },
    //关闭复制广告创意模态框的事件
    handleCopyClose() {
      this.visibleDup = false;
    },
    //改变单条广告系列状态
    handleSwitchState(record) {
      this.loading = true; //开启等待动画
      if (record.detailedState === NOTACTIVE) {
        record.detailedState = EXECUTABLE;
      } else {
        record.detailedState = NOTACTIVE;
      }
      let StateArr = [record.id];
      changeState({
        ids: StateArr,
        status: record.detailedState
      })
        .then(res => {
          if (res.data.data) {
            this.fetch();
            this.$message.info(this.$t("pro.campaigns.statusUpdate"));
          }
        })
        .catch(err => {
          this.loading = false; //关闭等待动画
        });
    },
    //多选开启活动状态
    handlechangeState(status) {
      let that = this;
      if (this.selectedRowKeys.length > 0) {
        //判断广告都为已经批准通过的广告
        let execuTable = [];
        execuTable = this.selectedRow.filter(item => {
          return (
            item.detailedState == NOTACTIVE || item.detailedState == EXECUTABLE
          ); //返回已经批准通过的广告
        });
        if (execuTable.length > 0) {
          //如果有已经通过审核的广告
          let stateArr = [];
          stateArr = execuTable.map(item => {
            if (item.detailedState !== status) {
              return item.id;
            }
          });
          if (stateArr[0] == undefined) {
            //如果没有符合条件的广告id数组
            status == EXECUTABLE
              ? that.$message.warning(this.$t("pro.Creatives.allActive"))
              : "";
            status == NOTACTIVE
              ? that.$message.warning(this.$t("pro.Creatives.allNotActive"))
              : "";
          } else {
            this.loading = true; //开启等待动画
            changeState({
              ids: stateArr,
              status: status
            })
              .then(res => {
                if (res.data.data) {
                  this.fetch();
                  this.selectedRowKeys = [];
                  this.$message.info(this.$t("pro.campaigns.statusUpdate"));
                  this.loading = false; //关闭等待动画
                }
              })
              .catch(() => {});
          }
          this.selectedRowKeys = [];
        } else {
          this.$message.warning(this.$t("pro.Creatives.passAuditMess"));
          this.selectedRowKeys = [];
        }
      } else {
        this.$warning({
          title: that.$t("pro.Creatives.SelectAction"),
          width: 500,
          okText: that.$t("pro.public.buttonClose"),
          onOk() {}
        });
      }
    },
    //查找已经激活的广告
    handleSelectActive(status) {
      this.loading = true;
      this.fetch({ status: status });
    },
    //查找所有的广告
    handleSelectAll() {
      this.loading = !this.loading;
      this.fetch();
    },
    onOpenChange() {
      this.openSetting = !this.openSetting;
    },
    saveCheckbox() {
      if (!this.columnsNoChange) {
        this.plainOptions.length = 0;
        let arr = this.checkedList.sort((a, b) => {
          return a - b;
        });
        arr.forEach(item => {
          this.plainOptions.push(item);
        });
        this.fetch();
        this.onOpenChange();
      }
    },
    checkedChange(value) {
      this.checkedList = value;
      this.columnsNoChange = false;
    }
  },
  mounted() {
    if (this.$parent.campaignsStatus == null) {
      this.campaignsStatus = this.isStatus;
    } else {
      this.campaignsStatus = this.$parent.campaignsStatus;
    }
    this.fetch();
  },
  beforeCreate() {
    statusMap = this.$t("pro.Creatives.statusMap");
  },
  // 监听表格creatives数据变化
  watch: {
    data() {
      this.data.forEach(creative => {
        creative.iabsize = creative.iabsize
          ? creative.iabsize.replace(",", " x ")
          : creative.iabsize;
      });
    },
    islocale(newval) {
      // if (newval == 'cn') {
      statusMap = this.$t("pro.Creatives.statusMap");
      this.columns.length = 0;
      this.$t("pro.Creatives.columnsplainOptions").forEach(item => {
        let { campaignsStatus } = this.$route.query || {};
        if (item != 3 || campaignsStatus !== "archived") {
          this.columns.push(this.$t("pro.Creatives.columnsPlainShadow")[item]);
        }
      });
      // } else {
      //     statusMap = this.$t('pro.Creatives.statusMap');
      //     this.columns.length = 0;
      //     this.$t('pro.Creatives.columnsplainOptions').forEach(item =>{
      //         this.columns.push(this.$t('pro.Creatives.columnsPlainShadow')[item])
      //     });
      // }
    }
  }
};
</script>

<style lang="less" scoped>
// @import "@/assets/css/colors.scss";
.ant-btn.ant-btn-loading:before {
  /* margin-left: -20px; */
  display: none;
}

.NotDuplicate {
  padding-bottom: 20px;
  background-color: #fbe1e3;
  color: #ef8088;
  margin-bottom: 20px;
}

.selectCreatives {
  grid-template-columns: repeat(3, auto);
}

h1,
h3 {
  margin-bottom: 0;
}

.buttongrid {
  justify-items: end;
  display: grid;
}

.Creativesgrid {
  width: 100%;
  grid-template-columns: 50% 47%;
}

@media screen and (max-width: 1200px) {
  .tools.flex-between {
    display: block;
    > div:not(:last-child) {
      margin-bottom: 10px;
    }
    .tools-r {
      display: flex;
      justify-content: flex-end;
      flex-wrap: wrap;
      align-items: center;
      > *:not(:first-child) {
        margin-left: 10px;
      }
      > * {
        margin-bottom: 5px;
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .tools.flex-between {
    display: block;
    > div:not(:last-child) {
      margin-bottom: 10px;
    }
    .tools-l {
      grid-template-columns: repeat(2, 1fr);
      > *:nth-child(1) {
        grid-column: 1;
        grid-row: 1;
      }
      > *:nth-child(2) {
        grid-column: 2;
        grid-row: 1;
      }
      > *:nth-child(3) {
        grid-column: 3;
        grid-row: 1;
      }
      > *:nth-child(4) {
        grid-column: 1 / 4;
      }
    }
  }
}

@media screen and (max-width: 500px) {
  .tools.flex-between {
    .tools-l {
      grid-template-columns: repeat(2, 1fr);
      > *:nth-child(1) {
        grid-column: 1;
        grid-row: 1;
      }
      > *:nth-child(2) {
        grid-column: 2;
        grid-row: 1;
      }
      > *:nth-child(3) {
        grid-column: 1;
        grid-row: 2;
      }
      > *:nth-child(4) {
        grid-column: 2;
        grid-row: 2;
      }
    }
  }
}

@media screen and (max-width: 320px) {
  .portlet {
    // background-color: #fff;
    padding: 12px 15px 15px;
  }
}

.ant-checkbox-wrapper:first-child {
  margin-left: 8px;
}

.setting-group {
  margin-bottom: 10px;
  grid-template-columns: 1fr 600px;
  .setting-group-wrapper {
    grid-column: 2;
    grid-row: 1;
    .checkbox-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
    }
    > button {
      margin-top: 10px;
    }
  }
}

@media screen and(max-width: 700px) {
  .setting-group {
    // display: grid;
    grid-template-columns: 1fr;
    .setting-group-wrapper {
      grid-column: 1;
      grid-row: 1;
      .checkbox-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}
</style>
